package com.cskt.petproject178.service.third;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cskt.petproject178.config.AliyunOSSAutoConfigProperties;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URL;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 阿里云OSS service
 **/

@Service
public class AliyunOSSService {
    private static  final Logger log= LoggerFactory.getLogger(AliyunOSSService.class);
    @Resource
    private AliyunOSSAutoConfigProperties properties;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 根据OSS对象名获取访问路径
     * @param objName
     * @return
     */
    public String getObjUrl(String objName) {

        //判断redis中是否存在对应的url路径
        String ossKey="pet:oss:"+objName;
        String ossUrl = stringRedisTemplate.opsForValue().get(ossKey);
        if (StringUtils.hasText(ossUrl)){
            return ossUrl;
        }
        //初始化oss客户端
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getSecretAccessKey());
        //计算过期时间
        Instant localDateTime = LocalDateTime.now().plusMinutes(30L)
                //将当前时间转换为Instant
                .toInstant(ZoneOffset.ofHours(8));

        Date expireTime=Date.from(localDateTime);
        //将instant转换成为data类型，得到过期时间
        URL url = ossClient.generatePresignedUrl(properties.getBucketName(), objName, expireTime);
        //将url存入redis中,并设置过期时间为29分钟，提前过期，重新获取
        stringRedisTemplate.opsForValue().set(ossKey,url.toString(),29, TimeUnit.MINUTES);
        log.info("获取阿里云OSS对象访问路径,url:{}",url.toString());
        return url.toString();
    }
}
